package com.rambler.common.core.controller;

import com.rambler.common.core.dto.UserDTO;
import com.rambler.common.entity.GlobalConst;
import com.rambler.common.core.entity.SystemUser;
import com.rambler.common.response.CommonResponse;
import com.rambler.common.core.service.SystemUserService;
import com.rambler.common.utils.JWTUtil;
import com.rambler.common.core.vo.SystemUserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @author suhao
 * @date 2025/7/28
 * @description 用户控制层
 */
@Slf4j
@RestController
@RequestMapping("/system/user")
public class UserController {

    @Value("${system.accessTokenExpireHours}")
    private String tokenExpireHours;

    @Value("${system.refreshTokenExpireHours}")
    private String refreshTokenExpireHours;

    @Resource
    private SystemUserService userService;

    @Operation(summary = "登录验证")
    @RequestMapping(value = "oauth", method = RequestMethod.POST)
    public CommonResponse<SystemUserVO> login(
            @RequestBody @Valid @Parameter(name = "用户", description = "用户实体类json格式", required = true) UserDTO user,
            HttpServletRequest request) {
        try {
            SystemUserVO vo = new SystemUserVO();
            SystemUser result = userService.login(user);
            result.setPassword("");
            vo.setUser(result);
            // access_token, refresh_token, token_expires
            HttpSession session = request.getSession();
            // 有效时间为8个小时
            session.setMaxInactiveInterval(60 * 60 * Integer.parseInt(tokenExpireHours));
            session.setAttribute(GlobalConst.CURRENT_USER, result);
            HashMap<String, String> payload = new HashMap<>();
            payload.put("id", result.getId());
            payload.put("username", result.getUsername());
            payload.put("avatar", result.getAvatar());
            vo.setAccessToken(JWTUtil.getToken(payload, Integer.parseInt(tokenExpireHours)));
            vo.setRefreshToken(JWTUtil.getToken(payload, Integer.parseInt(refreshTokenExpireHours)));
            vo.setTokenExpires(Long.parseLong(tokenExpireHours));
            return CommonResponse.success("登录成功", vo);
        } catch (Exception e) {
            return CommonResponse.failure(e.getMessage());
        }
    }

    @PostMapping("register")
    public CommonResponse<?> register(@RequestBody UserDTO request) {
        userService.register(request);
        return CommonResponse.success("注册成功");
    }

//    @Operation(summary = "解析token, 获取用户信息")
//    @Parameter(name = "token", description = "token", required = true)
//    @RequestMapping(value = "info", method = RequestMethod.GET)
//    public Response<UserVO> login(@RequestParam String token, HttpServletRequest request) {
//        String id = JWTUtil.tokenParse(token, "id");
//        if (id != null) {
//            // 解析token获取roles和用户信息
//            UserVO vo = new UserVO();
//            SystemUser user = userService.selectById(id);
//            vo.setAvatar(user.getAvatar());
//            vo.setUsername(user.getUsername());
//            vo.setIntroduction("");
//            // 角色信息
//            List<Role> roles = userRoleService.getRolesByUid(id);
//            List<String> roleList = new ArrayList<>();
//            for (Role r : roles) {
//                roleList.add(r.getRoleName());
//            }
//            vo.setRoles(roleList);
//            // 菜单权限
//            List<Menu> menuList = roleMenuService.getMenuListByRoles(roles);
//            vo.setMenus(menuList);
//            return Response.createSuccessResponse(vo);
//        }
//        return Response.createErrorResponse(null);
//    }

//    @ApiOperation(value = "注销账户", notes = "不需要参数")
//    @RequestMapping(value = "quit", method = RequestMethod.GET)
//    public Response<User> logout() {
//        int result = userService.logout();
//        if (result > 0) {
//            return Response.createSuccessResponse(null);
//        }
//        return Response.createErrorResponse("注销失败,当前用户未登录");
//    }
//
//    @ApiOperation(value = "通过主键查询单条数据")
//    @ApiImplicitParam(name = "id", value = "实体id", required = true, paramType = "query")
//    @RequestMapping(value = "selectOne", method = RequestMethod.GET)
//    public Response<User> selectOne(String id) {
//        if (id == null) {
//            return Response.createErrorResponse("参数错误");
//        }
//        User result = userService.selectById(id);
//        if (result != null) {
//            return Response.createSuccessResponse("查询成功", result);
//        }
//        return Response.createErrorResponse("查询失败");
//    }

//    @ApiOperation(value = "发布新增实体类")
//    @RequestMapping(value = "insert", method = RequestMethod.POST)
//    public Response<User> insert(@RequestBody @ApiParam(name = "文章对象", value = "json格式", required = true) User user) {
//        int result = userService.insert(user);
//        if (result > 0) {
//            return Response.createSuccessResponse("新增成功", user);
//        }
//        return Response.createErrorResponse("新增失败");
//    }
//
//    @ApiOperation(value = "更新用户角色信息")
//    @RequestMapping(value = "updateUserRole", method = RequestMethod.PUT)
//    public Response<Object> updateUserRole(@RequestBody @ApiParam(name = "用户角色权限实体") UserRoleDTO payload) {
//        String userId = payload.getUserId();
//        // 清空现有的关系，重新建立关系
//        Map<String, String> param = new HashMap<>();
//        param.put("userId", userId);
//        userRoleService.clearRelationByMap(param);
//        int count = 0;
//        String roleIds = payload.getRoleIds();
//        if (roleIds != null && !roleIds.equals("")) {
//            String[] ids = payload.getRoleIds().split(",");
//            for (String id : ids) {
//                count += userRoleService.insert(userId, id);
//            }
//        }
//        return Response.createSuccessResponse("分配" + count + "个角色成功", null);
//    }
//
//    @ApiOperation(value = "更新实体")
//    @RequestMapping(value = "update", method = RequestMethod.PUT)
//    public Response<User> update(@RequestBody @ApiParam(name = "文章对象", value = "json格式", required = true) User user) {
//        int result = userService.update(user);
//        if (result != -1) {
//            return Response.createSuccessResponse("修改成功", null);
//        }
//        return Response.createErrorResponse("修改失败");
//    }
//
//    @ApiOperation(value = "通过id删除")
//    @ApiImplicitParam(name = "ids", value = "实体id,多个id用英文逗号分割", required = true, paramType = "query")
//    @RequestMapping(value = "delete", method = RequestMethod.DELETE)
//    public Response<User> delete(String ids) {
//        if (ids == null) {
//            return Response.createErrorResponse("参数错误");
//        }
//        int result = userService.batchDelete(ids);
//        if (result > 0) {
//            return Response.createSuccessResponse("删除成功", null);
//        }
//        return Response.createErrorResponse("删除失败");
//    }
//
//    @ApiOperation(value = "查询所有", notes = "不需要参数")
//    @RequestMapping(value = "selectAll", method = RequestMethod.GET)
//    public Response<List<User>> selectAll() {
//        List<User> userList = userService.selectAll();
//        if (userList != null) {
//            return Response.createSuccessResponse("查询成功", userList);
//        }
//        return Response.createErrorResponse("查询失败");
//    }
//
//    @ApiOperation(value = "查询用户所有角色")
//    @ApiImplicitParam(name = "id", value = "用户id", required = true, paramType = "query")
//    @RequestMapping(value = "getRoles", method = RequestMethod.GET)
//    public Response<List<Role>> getRoles(String id) {
//        List<Role> roles = userRoleService.getRolesByUid(id);
//        return Response.createSuccessResponse(roles);
//    }
//
//    @ApiOperation(value = "分页查询")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "start", value = "开始位置,正整数", required = true, paramType = "query"),
//            @ApiImplicitParam(name = "limit", value = "页面大小,正整数", required = true, paramType = "query"),
//            @ApiImplicitParam(name = "用户名", value = "用户名", required = false, paramType = "query"),
//    })
//    @RequestMapping(value = "selectPage", method = RequestMethod.GET)
//    public Response<Page<User>> selectPage(Integer start, Integer limit, String username) {
//        if (start < 0 || limit <= 0) {
//            return Response.createErrorResponse("分页参数错误");
//        }
//        HashMap<String, String> param = new HashMap<>();
//        param.put("username", username);
//        List<User> userList = userService.selectPage(start, limit, param);
//        Page<User> page = new Page<>((start / limit) + 1, limit);
//        page.setRecords(userList);
//        page.setTotal(userService.count());
//        if (userList != null) {
//            return Response.createSuccessResponse("查询成功", page);
//        }
//        return Response.createErrorResponse("查询失败");
//    }
}
